package com.jwater.core.manager.common;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jwater.launch.HomePath;
import com.jwater.launch.JwaterLauncher;

import jwater.org.springframework.util.StringUtils;

/**
 * @description: 罗列日志信息
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class ListLogUtils {
    protected static Logger logger = LoggerFactory.getLogger(ListLogUtils.class);

    /**
     * 罗列日志文件
     *
     * @param regionName
     * @param dir
     * @return
     */
    public static List<String> listLog(String regionName, String dir) {
        List<String> list = new ArrayList<>();
        if (StringUtils.isEmpty(dir)) {
            boolean all = false;
            if (JwaterLauncher.DEFAULT_REGION_NAME.equals(regionName)) {
                all = true;
            }
            String logDir = HomePath.getLog();
            if (all) {
                listLogs(list, new File(logDir), true);
            } else {
                listLogs(list, new File(logDir, regionName), true);
                listLogs(list, new File(logDir, "bootstrap"), true);
                listLogs(list, new File(logDir, "console"), true);
                listLogs(list, new File(logDir, "master"), true);
                listLogs(list, new File(logDir, "proxy"), true);
            }
        } else {
            File dirFile = new File(HomePath.getLog(), dir);
            if (dirFile.exists()) {
                listLogs(list, dirFile, true);
                if ("/master".equals(dir)) {
                    listLogs(list, new File(HomePath.getLog(), "console"), true);
                }
            } else {
                logger.warn("file not exists for:" + dirFile.getPath());
            }
        }
        return list;
    }

    private static void listLogs(List<String> list, File dir, boolean recursive) {
        File[] files = dir.listFiles();
        if (files == null) {
            return;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                if (recursive) {
                    listLogs(list, file, recursive);
                }
            } else {
                if (file.getName().endsWith(".log") || file.getName().endsWith(".err")) {
                    list.add(file.getPath().replace("\\", "/"));
                }
            }
        }
    }
}
